//
//  Person.swift
//  SwiftFMDB
//
//  Created by 王冲 on 2018/5/7.
//  Copyright © 2018年 希艾欧科技有限公司. All rights reserved.
//

import UIKit

class Person: NSObject {

    @objc var id: Int = 0
    @objc var name: String?
    @objc var age: Int = 0
    
    
    // MARK: 系统内部的方法
    init(dict: [String:AnyObject]) {
        super.init()
        
        setValuesForKeys(dict)
    }
    
    override init()
    {
        super.init()
    }
    
    override func setValue(_ value: Any?, forUndefinedKey key: String)
    {
        print("\(key)")
    }
    
    override var description: String{
        
        return "id = \(id),age = \(age),name = \(name!)"
    }
    
    // MARK: 执行数据源 CRUD的操作
    /**
     插入一条数据
     */
    func insertPerson() -> Bool {
        
        assert(name != nil, "必须要给name赋值")
        
        // 1、编写SQLite语句
        let sql = "INSERT INTO T_Person (name,age) VALUES ('\(name!)',\(age));"
        // 2、执行SQLite语句
        return JKSQLiteManger.shareManger().db!.executeUpdate(sql, withArgumentsIn: [])
        
    }
    
    /**
     插入一条数据（预编译的）
     */
    func insertPerson2() -> Bool {
        
        assert(name != nil, "必须要给name赋值")
        
        // 1、编写SQLite语句
        let sql = "INSERT INTO T_Person (name,age) VALUES (?,?);"
        // 2、执行SQLite语句
        return JKSQLiteManger.shareManger().db!.executeUpdate(sql: sql, name! as AnyObject,age as AnyObject)
        
    }
    
    // MARK: 更新数据
    func updatePerson() -> Bool {
        
        // 1、编写SQLite语句
        let sql = "UPDATE T_Person SET name = '\(name!)' WHERE age = \(self.age);"
        // 2、执行SQLite语句
        return JKSQLiteManger.shareManger().db!.executeUpdate(sql, withArgumentsIn: [])
    }
    
    // MARK: 删除数据
    func deletePerson() -> Bool {
        
        // 1、编写SQLite语句
        let sql = "DELETE FROM T_Person WHERE age = \(self.age);"
        // 2、执行SQLite语句
        return JKSQLiteManger.shareManger().db!.executeUpdate(sql, withArgumentsIn: [])
    }
    
    // MARK: 查询数据
    // MARK: - 执行数据源CRUD的操作
    
    class func loadPersons() -> [Person]
    {
        let sql = "SELECT * FROM T_Person8;"
        let res = JKSQLiteManger.shareManger().db!.executeQuery(sql, withArgumentsIn: [])
        var models = [Person]()
        
        while res!.next() {
            
            let p = Person()
            p.id = res?.int(forColumn: "id") as! Int
            p.name = res?.string(forColumn: "name")
            p.age = res?.int(forColumn: "age") as! Int
            
            models.append(p)

        }
        
        return models
    }
    
}
